<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>13_节流-获取返回值</title>
  </head>

  <body>
    <button>按钮</button>

    <input type="text" />
    <button class="cancel">取消</button>

    <script>
      function throttle(fn, interval, { leading = false, trailing = true }) {
        let startTime = 0
        let timer = null
        const _throttle = function (...args) {
          return new Promise((resolve, reject) => {
            try {
              const nowDate = new Date().getTime()
              if (!leading && startTime === 0) {
                startTime = nowDate
              }

              const waitTimeFlag = nowDate - startTime >= interval
              if (waitTimeFlag) {
                if (timer) clearTimeout(timer)
                resolve(fn.apply(this, args))
                startTime = nowDate
                timer = null
                return
              }

              if (trailing && !timer) {
                timer = setTimeout(() => {
                  resolve(fn.apply(this, args))
                  startTime = new Date().getTime()
                  timer = null
                }, interval)
              }
            } catch (err) {
              reject(err)
            }
          })
        }

        _throttle.cancel = function () {
          if (timer) clearTimeout(timer)
          startTime = 0
          timer = null
        }

        return _throttle
      }
      let counter = 1

      const inputEl = document.querySelector('input')
      const cancelBtn = document.querySelector('.cancel')
      const throttleFn = throttle(
        function (event) {
          console.log(`发送了第${counter++}次网络请求`, this.value, event)
        },
        1000,
        { leading: true, trailing: true }
      )

      inputEl.oninput = throttleFn

      cancelBtn.onclick = function () {
        throttleFn.cancel()
      }

      // const throttleFn = throttle(
      //   function (event) {
      //     console.log(`发送网络请求${counter++}:`, event)
      //     return 'throttle return value'
      //   },
      //   3000,
      //   { trailing: true }
      // )

      // throttleFn('param throttle').then((res) => {
      //   console.log('res:', res)
      // })
    </script>
  </body>
</html>
